package org.meow.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.AeadAlgorithm;
import io.jsonwebtoken.security.KeyAlgorithm;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.Password;
import org.meow.constant.MsgConstant;

import java.util.Date;
import java.util.Map;

/**
 * &#064;Date: 24/05/14-13:09
 * &#064;Description: 已内置发布者，自动验证
 */
public class JwtUtil {

  // TODO: 发布时更改算法
  public static String createJwt(String pswd, long ttlMillis, Map<String, Object> claims) {

    Password                         password = Keys.password(pswd.toCharArray());
    KeyAlgorithm<Password, Password> alg      = Jwts.KEY.PBES2_HS512_A256KW;
    AeadAlgorithm                    enc      = Jwts.ENC.A256GCM;

    long expMillis = System.currentTimeMillis() + ttlMillis;
    Date exp       = new Date(expMillis);

    return Jwts.builder()
               .expiration(exp)
               .claims(claims)
               .issuer("meow")
               .encryptWith(password, alg, enc)
               .compact();
  }

  public static Claims parseJwt(String pswd, String jwe) throws Exception {
    Password password = Keys.password(pswd.toCharArray());
    return Jwts.parser()
               .decryptWith(password)
               .requireIssuer("meow")
               .build()
               .parseEncryptedClaims(jwe)
               .getPayload();
  }
}
